<template>
    <div class="app-container">
        <!-- 表格-条件筛区域  -->
        <div class="filter-container">
            <el-input placeholder="请输入赛事名称" v-model="searchParam.SEARCH_LIKE_name" style="width: 200px;"
                      class="filter-item" @keyup.enter.native="handleFilter"/>
            <el-cascader placeholder="请选择所属地区" ref="areaCascade" :options="areaData" :props="props" clearable
                         separator="—" @change="handleChange" v-model="searchParam.SEARCH_EQ_area" class="filter-item"
                         @keyup.enter.native="handleFilter" style="width: 300px"/>
            <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter"> 搜索</el-button>
            <el-button class="filter-item" type="default" icon="el-icon-search" @click="searchReset"> 重置</el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                       @click="handleCreate"> 新增
            </el-button>
        </div>

        <!-- 表格-内容区域 -->
        <el-table v-loading="listLoading" :key="tableKey" :data="tableList" border fit highlight-current-row
                  style="width: 100%;">
            <el-table-column v-for="column in columns" :key="column.prop"
                             :prop="column.prop"
                             :label="column.label"
                             :width="column.width"
                             :align="column.align?column.align:'center'"
                             :min-width="column.minWidth"
                             :sortable="column.sortable"
                             :fixed="column.fixed"
                             :type="column.type" :formatter="column.formatter">
                <template slot-scope="scope">
                    <!-- 行内显示图片 -->
                    <img v-if="column.imgFlag===true"
                         :src=" scope.row[column.prop].indexOf('http://') >-1 ?  scope.row[column.prop] : ( CMBASE.baseFileContext + scope.row[column.prop] ) "
                         width="60" height="60" class="img" alt=""/>
                    <!-- 行内显示开关按钮 -->
                    <el-switch v-else-if="column.switchFlag===true" v-model="scope.row[column.prop]" :active-value="1"
                               :inactive-value="0" disabled></el-switch>
                    <!-- 行内显示tag标签 -->
                    <span v-else-if="column.tagFlag===true">
                        <span v-for="item in column.tagFormatter" :key="item.value">
                            <el-tag v-if="item.value===scope.row[column.prop]" :type="item.type">{{
                                    item.text
                                }}</el-tag>
                        </span>
                    </span>
                    <!-- 行内格式自定义 -->
                    <span v-else-if="column.formatter"> {{ column.formatter(scope.row) }}</span>
                    <span v-else-if="column.prop === 'itemIds'">
                        {{ scope.row['itemIds'] | formatItemId(allItemList) }}
                    </span>
                    <span v-else-if="column.prop === 'type'">
                        {{ scope.row['type'] | formatTypeId(typeList) }}
                    </span>
                    <!--默认显示文本-->
                    <span v-else>{{ scope.row[column.prop] }}</span>
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="280" class-name="small-padding"  fixed ="right">
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="handleUpdate(scope.row)"> 编辑</el-button>
                    <el-button type="danger" size="mini" @click="handleDelete(scope.row)"> 删除</el-button>
                    <el-button type="primary" size="mini" @click="handleSetFormatLive(scope.row.id,scope.row.matchGroup,scope.row.cu,scope.row.itemIds)"> 赛程直播间</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 表格-页脚区域 -->
        <pagination v-show="tableTotal>0" :total="tableTotal" :page.sync="pageRequest.pageNum"
                    :limit.sync="pageRequest.pageSize" @pagination="getList"/>

        <!--新增编辑界面-->
        <el-dialog :title="operation?'新增':'编辑'" width="60%" top="5vh" :visible.sync="dialogFormVisible"
                   :close-on-click-modal="false" z-index="1999">
            <el-form :model="dataForm" label-width="140px" :rules="dataFormRules" ref="dataForm" style="width: 80%">

                <el-form-item label="赛事名称" prop="name">
                    <el-input v-model="dataForm.name" auto-complete="off" placeholder="请输入赛事名称"/>
                </el-form-item>
                <el-form-item label="地区" prop="provinceCode">
                    <area-cascade v-model="areaCasResult"/>
                </el-form-item>
                <el-form-item label="赛事分类" prop="type">
                    <el-select v-model="dataForm.type" placeholder="请选择赛事分类" @change="handleTypeChange">
                        <el-option v-for="type in typeList"
                                   :key="type.id"
                                   :label="type.name"
                                   :value="type.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="比赛要求" prop="description">
                    <el-input type="textarea" v-model="dataForm.description" maxlength="200" show-word-limit  placeholder="请输入比赛要求"/>
                </el-form-item>
                <el-form-item label="赛事轮播图" prop="bannerList">
                    <cm-upload-more v-model="dataForm.bannerList" :limit="3" ></cm-upload-more>
                </el-form-item>
                <el-form-item label="参赛范围" prop="matchGroup">
                    <el-select v-model="dataForm.matchGroup" placeholder="请选择参赛范围" @change="handlerMatchGroup">
                        <el-option label="单人" :value="1"></el-option>
                        <el-option label="团体" :value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="dataForm.matchGroup === 1" label="参赛人数" prop="signCount">
                    <el-input-number v-model="dataForm.signCount" @change="handleChange"
                                     :min="1" :max="1"></el-input-number>
                </el-form-item>
                <el-form-item v-if="dataForm.matchGroup === 2" label="参赛人数" prop="signCount">
                    <el-input-number v-model="dataForm.signCount" @change="handleChange"
                                     :min="1" :max="999"></el-input-number>
                </el-form-item>
                <el-form-item v-if="dataForm.matchGroup === 1" label="参赛类型" prop="matchType">
                    <el-select v-model="dataForm.matchType" @change="handlerMatchType"
                               placeholder="请选择参赛类型">
                        <el-option label="单人单项比赛" :value="1"></el-option>
                        <el-option label="单人多项比赛" :value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="dataForm.matchGroup === 2" label="参赛类型" prop="matchType">
                    <el-select v-model="dataForm.matchType" placeholder="请选择参赛类型" @change="handlerMatchType">
                        <el-option label="多人多项比赛" :value="3"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="dataForm.matchType === 1" label="参赛项目" prop="itemIdStr" >
                    <el-select  v-model="dataForm.itemIdStr" @change="$forceUpdate()"
                                placeholder="请选择参赛项目">
                        <el-option v-for="item in itemList"
                                   :key="item.id"
                                   :label="item.name"
                                   :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="dataForm.matchType === 2 || dataForm.matchType === 3" label="参赛项目" prop="itemIdStr" >
                    <!--                <el-form-item  label="参赛项目" prop="itemIdStr" >-->
                    <el-select   v-model="dataForm.itemIdStr" @change="$forceUpdate()" multiple style="width:680px"
                                 placeholder="请选择参赛项目">
                        <el-option v-for="item in itemList"
                                   :key="item.id"
                                   :label="item.name"
                                   :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="报名开始时间" prop="startTime">
                    <el-date-picker type="datetime" placeholder="选择日期" v-model="dataForm.startTime"
                                    value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss"
                                    style="width: 50%;"></el-date-picker>
                </el-form-item>
                <el-form-item label="报名结束时间" prop="endTime">
                    <el-date-picker type="datetime" placeholder="选择日期" v-model="dataForm.endTime"
                                    value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss"
                                    style="width: 50%;"></el-date-picker>
                </el-form-item>
                <el-form-item label="付费方式" prop="payType">
                    <el-radio-group v-model="dataForm.payType">
                        <el-radio :label="0">免费</el-radio>
                        <el-radio :label="1">可用金币</el-radio>
                        <el-radio :label="2">纯钱</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item v-if="dataForm.payType !== 0" label="报名价格" prop="signPrice">
                    <el-input-number v-model="dataForm.signPrice" @change="handleChange"
                                     :min="0" :max="99999"></el-input-number>
                </el-form-item>
                <el-form-item label="连麦时长" prop="chatTime">
                    <el-input-number v-model="dataForm.chatTime" @change="handleChange" controls-position="right"
                                     size="mini" :min="0" :max="999">
                    </el-input-number>
                    （分钟）
                </el-form-item>
                <el-form-item label="比赛权限" prop="isPublic">
                    <!--  （1不需要 0需要）  -->
                    <el-radio-group v-model="dataForm.isPublic">
                        <el-radio :label="1">公开</el-radio>
                        <el-radio :label="0">非公开</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="比赛规则" prop="matchNum">
                    <el-radio-group v-model="matchNum">
                        <el-radio :label="0">单场</el-radio>
                        <el-radio :label="1">晋级赛</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="设置赛程" prop="format">
                    <el-form :model="dataFormFormat" ref="dataFormFormat">
                        <!--  赛程信息动态增减  -->
                        <div v-for="(item,index) in dataFormFormat.formatList" :key="index"
                             style="border:  solid  1px  #ddd;  border-radius:  5px;  padding-top:  20px;padding-left: 50px">
                            <el-form-item label="开始时间"
                                          :prop="'formatList.' + index + '.startTime'"
                                          :rules="{required: true, message: '开始时间不能为空', trigger: 'blur'}">
                                <el-button type="danger" icon="el-icon-delete" circle
                                           style="float:right;margin-right:15px" @click="deleteItem(item, index)"/>
                                <el-date-picker type="datetime" placeholder="选择日期" v-model="item.startTime"
                                                value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss"
                                                style="width: 50%;"></el-date-picker>
                            </el-form-item>
                            <el-form-item label="结束时间"
                                          :prop="'formatList.' + index + '.endTime'"
                                          :rules="{required: true, message: '结束时间不能为空', trigger: 'blur'}">
                                <el-date-picker type="datetime" placeholder="选择日期" v-model="item.endTime"
                                                value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss"
                                                style="width: 50%;"></el-date-picker>
                            </el-form-item>
                            <el-form-item label="晋级方式" :prop="'formatList.' + index + '.updateType'"
                                          :rules="{required: true, message: '晋级方式不能为空', trigger: 'blur'}">
                                <!--  （1不需要 0需要）  -->
                                <el-radio-group v-model="item.updateType">
                                    <el-radio :label="0">自动</el-radio>
                                    <el-radio :label="1">手动</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="晋级人数"
                                          :prop="'formatList.' + index + '.promotionNum'"
                                          :rules="{required: true, message: '晋级人数不能为空', trigger: 'blur'}">
                                <el-input-number v-model="item.promotionNum" @change="handleChange"
                                                 :min="0" :max="99"></el-input-number>
                            </el-form-item>
                            <el-form-item label="晋级分数"
                                          :prop="'formatList.' + index + '.promotionScore'"
                                          :rules="{required: true, message: '晋级分数不能为空', trigger: 'blur'}">
                                <el-input-number v-model="item.promotionScore" @change="handleChange"
                                                 :min="0" :max="999"></el-input-number>
                            </el-form-item>
                        </div>
                        <el-button type="success" plain @click="addItem">添加赛程</el-button>
                    </el-form>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click.native="closeDialog()">取消</el-button>
                <el-button size="mini" @click.native="saveFormData()" :loading="editLoading" type="primary">提交
                </el-button>
            </div>
        </el-dialog>

        <!-- 赛程-->
        <el-dialog :title="formatListName" :visible.sync="getFormatListVisible" :close-on-click-modal="false"
                   width="65%" top="5vh" z-index="2000">
            <el-table v-loading="listLoadingFormat" :data="tableListFormat" border fit highlight-current-row
                      style="width: 100%;">
                <el-table-column
                    v-for="column in columnFormat"
                    :key="column.prop"
                    :prop="column.prop"
                    :label="column.label"
                    :width="column.width"
                    :align="column.align?column.align:'center'"
                    :min-width="column.minWidth"
                    :sortable="column.sortable"
                    :fixed="column.fixed"
                    :type="column.type"
                    :formatter="column.formatter">
                    <template slot-scope="scope">
                        <!-- 行内格式自定义 -->
                        <span v-if="column.formatter"> {{ column.formatter(scope.row) }}</span>
                        <!--默认显示文本-->
                        <span v-else>{{ scope.row[column.prop] }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="操作" align="center" width="240" class-name="small-padding">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="handleFormatLive(scope.row.id)"> 分配直播间</el-button>
                        <el-button type="primary" size="mini" @click="assignFormatMember(scope.row.id)"> 分配参赛员</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click.native="closeDialogFormat()">关闭</el-button>
            </div>
        </el-dialog>

        <!-- 分配直播间-->
        <el-dialog :title="liveListName" :visible.sync="getFormatLiveListVisible" :close-on-click-modal="false"
                   width="65%" top="5vh" z-index="2000">
            <div class="filter-container">
                <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                           @click="handleCreateLive"> 新增
                </el-button>
            </div>
            <el-table v-loading="listLoadingFormatLive" :data="tableListFormatLive" border fit highlight-current-row
                      style="width: 100%;">
                <el-table-column
                    v-for="column in columnFormatLive"
                    :key="column.prop"
                    :prop="column.prop"
                    :label="column.label"
                    :width="column.width"
                    :align="column.align?column.align:'center'"
                    :min-width="column.minWidth"
                    :sortable="column.sortable"
                    :fixed="column.fixed"
                    :type="column.type"
                    :formatter="column.formatter">
                    <template slot-scope="scope">
                        <!-- 行内显示图片 -->
                        <img v-if="column.imgFlag===true"
                             :src=" scope.row[column.prop].indexOf('http://') >-1 ?  scope.row[column.prop] : ( CMBASE.baseFileContext + scope.row[column.prop] ) "
                             width="60" height="60" class="img" alt=""/>
                        <!-- 行内格式自定义 -->
                        <span v-else-if="column.formatter"> {{ column.formatter(scope.row) }}</span>
                        <!--默认显示文本-->
                        <span v-else>{{ scope.row[column.prop] }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="操作" align="center" width="340" class-name="small-padding">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="handleUpdateLive(scope.row)"> 编辑</el-button>
                        <el-button type="danger" size="mini" @click="handleDeleteLive(scope.row)"> 删除</el-button>
                        <el-button type="primary" size="mini" @click="handleFormatLiveRecordUser(scope.row)"> 查看参赛员</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!--新增编辑界面-->
            <el-dialog :title="liveListName" width="45%" top="5vh" :visible.sync="dialogFormVisibleFormatLive"
                       :close-on-click-modal="false" z-index="2000">
                <el-form :model="dataFormFormatLive" :rules="dataFormRulesFormatLive" label-width="140px"
                         ref="dataFormFormatLive" style="width: 80%">
                    <el-form-item label="直播标题" prop="title">
                        <el-input v-model="dataFormFormatLive.title" auto-complete="off" placeholder="请输入直播标题"/>
                    </el-form-item>
                    <el-form-item label="主播" prop="liveId">
                        <el-select v-model="dataFormFormatLive.liveId" filterable  placeholder="请选择赛事主播"
                                   @change="handleTypeChange">
                            <el-option v-for="user in liveUserList"
                                       :key="user.liveId"
                                       :label="user.liveUser+'('+user.phone+')'"
                                       :value="user.liveId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="直播封面" prop="liveLogo">
                        <cm-upload v-model="dataFormFormatLive.liveLogo"></cm-upload>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button size="mini" @click.native="returnFormatLive()">取消</el-button>
                    <el-button size="mini" @click.native="saveFormDataLive()" :loading="editLoadingFormatLive"
                               type="primary">提交
                    </el-button>
                </div>
            </el-dialog>
            <!-- 表格-页脚区域 -->
            <pagination v-show="tableTotalFormatLive>0" :total="tableTotalFormatLive"
                        :page.sync="pageRequestFormatLive.pageNum"
                        :limit.sync="pageRequestFormatLive.pageSize" @pagination="showFormatLiveList"/>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click.native="closeDialogFormatLive()">关闭</el-button>
            </div>
        </el-dialog>

        <!-- 赛程直播间-分配直播间-查看参赛人员-->
        <el-dialog :title="matchGroup === 1?'个人赛事参赛人员':'团队赛事参赛人员'" :visible.sync="getFormatLiveRecordUserListVisible" :close-on-click-modal="false"
                   width="65%" top="5vh" z-index="2000">
            <el-table ref="serveTable" v-loading="listLoadingFormatLiveRecordUser" :data="tableListFormatLiveRecordUser" border fit highlight-current-row
                      style="width: 100%;" @selection-change="handleSelectionChange" @row-click="rowClick">
                <el-table-column  key="userName" prop="userName" label="用户名"   align="center" >
                </el-table-column>
                <el-table-column v-if="matchGroup===2" key="groupName" prop="groupName"  label="团队名称" align="center"   >
                </el-table-column>
                <el-table-column label="操作" align="center" width="240" class-name="small-padding">
                    <template slot-scope="scope">
                        <el-button v-if="scope.row.scoreCount === 0" type="danger" size="mini" @click="giveUpFormat(scope.row)">弃赛</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 表格-页脚区域 -->
            <pagination v-show="tableTotalFormatLiveRecordUser>0" :total="tableTotalFormatLiveRecordUser"
                        :page.sync="pageRequestFormatLiveRecordUser.pageNum"
                        :limit.sync="pageRequestFormatLiveRecordUser.pageSize" @pagination="showFormatLiveRecordUserList"/>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click.native="closeDialogFormatLiveRecordUser()">关闭</el-button>
            </div>
        </el-dialog>

        <!-- 分配参赛人员-->
        <el-dialog :title="liveUserListName" :visible.sync="getFormatLiveUserListVisible" :close-on-click-modal="false"
                   width="65%" top="5vh" z-index="2000">
            <el-form :model="dataFormFormatLiveUser" :rules="dataFormRulesFormatLiveUser" label-width="140px"
                     ref="dataFormFormatLiveUser" style="width: 80%">
                <el-form-item label="分配直播间" prop="recordId">
                    <el-select v-model="dataFormFormatLiveUser.recordId" placeholder="请选择直播间">
                        <el-option v-for="liveRecord in liveRecordList"
                                   :key="liveRecord.id"
                                   :label="liveRecord.title"
                                   :value="liveRecord.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <el-table ref="serveTable" v-loading="listLoadingFormatLiveUser" :data="tableListFormatLiveUser" border fit highlight-current-row
                      style="width: 100%;" @selection-change="handleSelectionChange" @row-click="rowClick">
                <el-table-column
                    type="selection"
                    width="55"
                    :selectable="selectable">
                </el-table-column>

                <!--                <el-table-column v-if="matchGroup===1" key="userId"  prop="userId" label="用户id"  align="center"  >-->
                <!--                </el-table-column>-->
                <el-table-column v-if="matchGroup===1" key="userName" prop="userName" label="用户名"   align="center" >
                </el-table-column>
                <el-table-column v-if="matchGroup===2" key="groupName" prop="groupName"  label="团队名称" align="center"   >
                </el-table-column>

                <el-table-column label="操作" align="center" width="240" class-name="small-padding">
                    <template slot-scope="scope">
                        <el-button v-if="matchGroup===1" type="danger" size="mini" @click="handleDeleteLiveUser(scope.row)"> 删除</el-button>
                        <el-button v-if="matchGroup===2" type="danger" size="mini" @click="handleDeleteGroupLiveUser(scope.row)"> 删除</el-button>
                        <el-button type="primary" size="mini" @click="viewFormatLiveUser(scope.row)" v-if="matchGroup===2"> 查看参赛人员</el-button>
                    </template>
                </el-table-column>

            </el-table>
            <!-- 表格-页脚区域 -->
            <pagination v-show="tableTotalFormatLiveUser>0" :total="tableTotalFormatLiveUser"
                        :page.sync="pageRequestFormatLiveUser.pageNum"
                        :limit.sync="pageRequestFormatLiveUser.pageSize" @pagination="showFormatLiveUserList"/>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click.native="closeDialogFormatLiveUser()">关闭</el-button>
                <el-button size="mini" type="primary" @click.native="assignFormatLiveUser()">分配</el-button>
            </div>
        </el-dialog>
        <!-- 分配参赛人员-团队下人员列表-->
        <el-dialog :title="formatMemberName" :visible.sync="getFormatMemberVisible" :close-on-click-modal="false"
                   width="55%" top="5vh" z-index="2000">
            <el-table v-loading="listLoadingFormatMember" :data="tableListFormatMember" border fit highlight-current-row
                      style="width: 100%;">
                <el-table-column
                    v-for="column in columnFormatMember"
                    :key="column.prop"
                    :prop="column.prop"
                    :label="column.label"
                    :width="column.width"
                    :align="column.align?column.align:'center'"
                    :min-width="column.minWidth"
                    :sortable="column.sortable"
                    :fixed="column.fixed"
                    :type="column.type"
                    :formatter="column.formatter">
                    <template slot-scope="scope">
                        <!-- 行内显示图片 -->
                        <img v-if="column.imgFlag===true"
                             :src=" scope.row[column.prop].indexOf('http://') >-1 ?  scope.row[column.prop] : ( CMBASE.baseFileContext + scope.row[column.prop] ) "
                             width="60" height="60" class="img" alt=""/>
                        <!-- 行内格式自定义 -->
                        <span v-else-if="column.formatter"> {{ column.formatter(scope.row) }}</span>
                        <!--默认显示文本-->
                        <span v-else>{{ scope.row[column.prop] }}</span>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 表格-页脚区域 -->
            <pagination v-show="tableTotalFormatMember>0" :total="tableTotalFormatMember"
                        :page.sync="pageRequestFormatLiveUser.pageNum"
                        :limit.sync="pageRequestFormatLiveUser.pageSize" @pagination="showFormatLiveUserList"/>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click.native="closeDialogFormatMember()">关闭</el-button>
            </div>
        </el-dialog>

    </div>

</template>
<script>
const areaList = require('./area')
import Pagination from '@/components/Pagination' // 分页栏信息
import {
    deleteFormatLive,
    deleteJdMatch,
    editFormatLive,
    editJdMatch,
    getFormatListPage,
    getFormatLiveList,
    getFormatLiveListPage,
    getJdMatchItemList,
    getJdMatchTypeList,
    getListByTypeId,
    getMatchFormatList,
    getViewMatchItemList,
    saveFormatLive,
    saveJdMatch,
    getFormatLiveUserList,
    getformatMemberList,
    deleteFormatLiveUser,
    handleDeleteGroupLiveUser,
    handleDeleteLiveUser,
    setMatchLiveUser,
    getFormatLiveRecordList,
    getFormatLiveUserListGroup,
    getFormatMemberListByGroupId,
    giveUpFormatList,
} from '@/api/modules/match'
import {getSysLiveUserList, inviteToBeAnchorById} from '@/api/modules/appUser'
import AreaCascade from '@/components/AreaCascade/indexMatch.vue'
import CmUpload from '@/components/Upload' // 上传图片组件引入
import CmUploadMore from '@/components/UploadMore' // 上传图片组件引入

export default {
    name: 'match',
    components: {
        Pagination,
        AreaCascade,
        CmUpload,
        CmUploadMore,
    },
    directives: {},
    filters: {
        formatItemId(value, List) {
            if (!value) return "";
            // const item = List.find(item => item.id === value)
            return List.filter(item => (value.indexOf(item.id) > -1)).map(item => item.name).join(",")
        },
        formatTypeId(value, List) {
            const item = List.find(item => item.id === value)
            return item ? item.name : ""
        }
    },
    data() {
        return {
            tableKey: 0,
            tableList: [],//表格数据源
            tableTotal: 0,//表格总条数数据
            listLoading: true,
            pageRequest: {pageNum: 1, pageSize: 10,},
            searchParam: {},
            dialogFormVisible: false,//默认不显示弹出框
            operation: true, // true:新增, false:编辑
            editLoading: false,//保存表单时loading框
            columns: [
                // {prop: 'id', label: '', sortable: false},
                {prop: 'mobile', label: '发布机构手机号', sortable: false},
                {prop: 'name', label: '赛事名称', sortable: false},
                // {prop: 'province', label: '省', sortable: false},
                // {prop: 'city', label: '市', sortable: false},
                // {prop: 'area', label: '县', sortable: false},
                {prop: 'type', label: '赛事分类', sortable: false},
                {prop: 'description', label: '比赛要求', sortable: false , width:"450px"},
                {prop: 'signCount', label: '参赛人数', sortable: false},
                {
                    prop: 'matchGroup', label: '参赛范围', sortable: false, tagFlag: true,
                    tagFormatter: [
                        {text: '单人', value: 1, type: 'success'},
                        {text: '团体', value: 2, type: 'warning'}
                    ]
                },
                {
                    prop: 'matchType', label: '参赛项目', sortable: false, tagFlag: true,width:150,
                    tagFormatter: [
                        {text: '单人单项比赛', value: 1, type: 'warning'},
                        {text: '单人多项比赛', value: 2, type: 'success'},
                        {text: '多人多项比赛', value: 3, type: 'error'},
                    ]
                },
                {prop: 'itemNames', label: '赛事项目', sortable: false},
                {
                    prop: 'payType', label: '付费方式', sortable: false, tagFlag: true,
                    tagFormatter: [
                        {text: '免费', value: 0, type: 'warning'},
                        {text: '可用金币', value: 1, type: 'success'},
                        {text: '纯钱', value: 2, type: 'success'}
                    ]
                },
                {prop: 'signPrice', label: '报名价格', sortable: false},
                {
                    prop: 'state', label: '状态', sortable: false, tagFlag: true,
                    tagFormatter: [
                        {text: '待审核', value: 0, type: 'warning'},
                        {text: '审核通过', value: 1, type: 'success'},
                        {text: '审核拒绝', value: 2, type: 'error'}
                    ]
                },
                {prop: 'startTime', label: '报名开始时间', sortable: false, width: 140},
                {prop: 'endTime', label: '报名结束时间', sortable: false, width: 140},
            ],
            fileList: [],
            matchNum:'',
            isPublic:'',
            // 新增编辑界面数据
            dataForm: {},
            //提交参赛人员表单
            liveUserDataForm: {},
            areaCasResult: {
                province: '',
                provinceCode: '',
                city: '',
                cityCode: '',
                country: '',
                countryCode: '',
            },
            //表单检验规则
            dataFormRules: {
                // id: [{required: true, message: '请输入', trigger: 'blur'}],
                name: [{required: true, message: '请输入赛事名称', trigger: 'blur'}],
                // province: [{required: true, message: '请选择省市县', trigger: 'blur'}],
                // provinceCode: [{required: true, message: '请选择省市县', trigger: 'blur'}],
                // city: [{required: true, message: '请输入市', trigger: 'blur'}],
                // cityCode: [{required: true, message: '请输入市', trigger: 'blur'}],
                // area: [{required: true, message: '请输入县', trigger: 'blur'}],
                // areaCode: [{required: true, message: '请输入县', trigger: 'blur'}],
                type: [{required: true, message: '请输入赛事分类', trigger: 'blur'}],
                description: [{required: true, message: '请输入比赛要求', trigger: 'blur'}],
                bannerList: [{required: true, message: '请输入赛事banner图', trigger: 'blur'}],
                signCount: [{required: true, message: '请输入参赛人数', trigger: 'blur'}],
                matchGroup: [{required: true, message: '请选择参赛范围', trigger: 'blur'}],
                matchType: [{required: true, message: '请选择参赛类型', trigger: 'blur'}],
                itemIds: [{required: true, message: '请选择参赛项目', trigger: 'blur'}],
                itemIdStr: [{required: true, message: '请选择参赛项目', trigger: 'blur'}],
                // payType: [{required: true, message: '请选择付费方式', trigger: 'blur'}],
                startTime: [{required: true, message: '请输入开始时间', trigger: 'blur'}],
                endTime: [{required: true, message: '请输入结束时间', trigger: 'blur'}],
                isPublic: [{required: true, message: '请输入比赛权限', trigger: 'blur'}],
                // matchNum: [{required: true, message: '请输入比赛规则', trigger: 'blur'}],
                // cu: [{required: true, message: '请输入创建机构', trigger: 'blur'}],
                // ct: [{required: true, message: '请输入创建时间', trigger: 'blur'}],
                // signPrice: [{required: true, message: '请输入报名价格', trigger: 'blur'}],
                // chatTime: [{required: true, message: '请输入报名价格', trigger: 'blur'}],
                // format: [{required: true, message: '请设置赛程', trigger: 'blur'}],
                // liveList: [{required: true, message: '请设置直播间', trigger: 'blur'}],
            },
            dataFormRulesFormatLiveUser:{
                liveUserList: [{required: true, message: '请选择参赛员列表', trigger: 'blur'}],
                recordId: [{required: true, message: '请选择直播间', trigger: 'blur'}],
            },

            //地址选择
            areaData: areaList,
            props: {
                multiple: false, // 是否多选
                emitPath: false,
                label: 'name',
                value: 'code',
                children: 'children'
            },
            //参赛项目列表
            itemList: [],
            allItemList: [],
            //赛事分类列表
            typeList: [],
            typeId: '',

            matchId: '',
            matchGroup: '',
            matchCu: '',
            matchItemIds: '',
            //弃赛集合
            scoreParamDataForm:{
                userId:'',
                itemId:'',
                formatId:'',
                scoreInfoList:[],
            },
            //赛程分配
            formatListName: '分配直播间',
            getFormatListVisible: false, // 属性值列表页 隐藏
            // dialogFormVisibleFormat: false, // 默认不显示弹出框
            listLoadingFormat: true,
            tableListFormat: [], // 表格数据源
            columnFormat: [
                {prop: 'startTime', label: '开始时间', sortable: false},
                {prop: 'endTime', label: '结束时间', sortable: false},
                {prop: 'arrangeOrder', label: '进行顺序', sortable: false, formatter:this.formatArrangeOrder},
                {prop: 'promotionNum', label: '晋级人数', sortable: false},
                {prop: 'promotionScore', label: '晋级分数', sortable: false},
            ],

            //赛程直播间分配
            formatId: '',
            liveRecordId: '',
            liveListName: '分配直播间',
            liveUserListName: '分配参赛员',
            formatMemberName: '团队参赛员列表',
            editLoadingFormatLive: false,//保存表单时loading框
            getFormatLiveListVisible: false, // 属性值列表页 隐藏
            getFormatLiveUserListVisible: false, // 已参赛人员 属性值列表页 隐藏
            getFormatMemberVisible: false, // 团队参赛人员 属性值列表页 隐藏
            dialogFormVisibleFormatUser: false, // 待参赛人员 属性值列表页 隐藏
            listLoadingFormatLive: true,
            listLoadingFormatMember: true,
            listLoadingFormatLiveUser: true,//已参赛人员
            listLoadingFormatUser: true,//待参赛人员
            tableTotalFormatLive: 0,
            tableTotalFormatMember: 0,//团队人员列表
            tableTotalFormatLiveUser: 0,//已参赛人员
            tableTotalFormatUser: 0,//待已参赛人员
            dataFormFormatLive: {},
            dataFormFormatLiveRecord: {},//提交分配参赛员表单
            dataFormFormatLiveUser: {},//已参赛人员
            tableListFormatLive: [], // 表格数据源
            tableListFormatMember: [], // 团队参赛人员表格数据源
            tableListFormatLiveUser: [], // 已参赛人员表格数据源
            tableListFormatUser: [], // 待参赛人员表格数据源
            pageRequestFormatLive: {pageNum: 1, pageSize: 10},
            pageRequestFormatLiveUser: {pageNum: 1, pageSize: 10},//已参赛人员
            pageRequestFormatUser: {pageNum: 1, pageSize: 10},//可参赛人员
            //直播间-分配的参赛员
            liveFormatLiveRecordUserListName:'查看参赛人员',
            getFormatLiveRecordUserListVisible:false,
            tableListFormatLiveRecordUser:[],
            listLoadingFormatLiveRecordUser:false,
            tableTotalFormatLiveRecordUser:0,
            pageRequestFormatLiveRecordUser: {pageNum: 1, pageSize: 10},
            dialogFormVisibleFormatLive: false, // 默认不显示弹出框
            dialogFormVisibleFormatLiveUser: false, // 已参赛人员
            columnFormatLive: [
                {prop: 'liveId', label: '主播', sortable: false},
                {prop: 'title', label: '直播标题', sortable: false},
                {prop: 'liveLogo', label: '直播图片', sortable: false, imgFlag: true},
                {prop: 'startTime', label: '开始时间', sortable: false},
                {prop: 'endTime', label: '结束时间', sortable: false},
            ],
            columnFormatMember: [
                {prop: 'userName', label: '用户名', sortable: false},
                {prop: 'mobile', label: '手机号', sortable: false},
                // {prop: 'headImg', label: '头像', sortable: false},
                {prop: 'groupName', label: '团队名称', sortable: false},
            ],

            columnFormatUser:[
                {prop: 'userId', label: '用户id', sortable: false},
                {prop: 'userName', label: '用户名', sortable: false},
                // {prop: 'headImg', label: '头像', sortable: false},
                {prop: 'groupName', label: '团队名称', sortable: false},
            ],
            dataFormRulesFormatLive: {
                liveId: [{required: true, message: '请选择主播', trigger: 'blur'}],
                title: [{required: true, message: '请输入直播标题', trigger: 'blur'}],
                liveLogo: [{required: true, message: '请输入直播图片', trigger: 'blur'}],
                startTime: [{required: true, message: '请输入开始时间', trigger: 'blur'}],
                endTime: [{required: true, message: '请输入结束时间', trigger: 'blur'}],
            },
            //动态删除赛程集合
            delFormatList:[],
            // 动态增加赛程界面数据
            dataFormFormat: {
                formatList: [{
                    id:'',
                    startTime: '',
                    endTime: '',
                    promotionNum: '',
                    promotionScore: '',
                    updateType: '',
                }]
            },
            //所有主播
            liveUserList: {},
            //所有直播间
            liveRecordList:{},
            liveUserIds: [],
            multipleSelection:{},
            formatMemberPageParam : {
                id:"",
                arrangeId: ""
            }
        }
    },
    watch: {
        // 省、市、区数据回显
        areaCasResult: {
            immediate: true,
            handler(val) {
                if((val.provinceCode === '1' && !val.province ) || (val.cityCode === '2' && !val.city) || (val.countryCode === '3' && !val.country)){
                    if(val.provinceCode === '1'){
                        this.dataForm.provinceCode = ''
                        this.dataForm.cityCode = ''
                        this.dataForm.areaCode = ''
                    }
                    if(val.cityCode === '2'){
                        this.dataForm.provinceCode = val.provinceCode
                        this.dataForm.cityCode = ''
                        this.dataForm.areaCode = ''
                    }
                    if(val.countryCode === '3'){
                        this.dataForm.provinceCode = val.provinceCode
                        this.dataForm.cityCode = val.cityCode
                        this.dataForm.areaCode = ''
                    }
                }else{
                    this.dataForm.province = val.province
                    this.dataForm.provinceCode = val.provinceCode
                    this.dataForm.city = val.city
                    this.dataForm.cityCode = val.cityCode
                    this.dataForm.area = val.country
                    this.dataForm.areaCode = val.countryCode
                    this.dataForm.address = val.address
                }
            }
        }
    },
    methods: {
        //是否禁用复选框
        selectable(row) {
            if (row.liveRecordId === null) {
                return true;
            } else {
                return false;
            }
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        rowClick(row, column, event) {
            let refsElTable = this.$refs.serveTable; // 获取表格对象
            let findRow = this.multipleSelection.find(c => c.rowIndex == row.rowIndex);  //找到选中的行
            if (findRow ) {
                refsElTable.toggleRowSelection(row, false);  //如过重复选中，则取消选中
                return;
            }
            refsElTable.toggleRowSelection(row,true); // 实现选中行中选中事件
        },
        handleChange(value) {
            // console.log(value);
            // this.dataForm.itemIdStr = []
        },
        handleTypeChange(value) {
            this.getItemList(value)
        },
        //获取表格数据
        getList() {
            this.listLoading = true
            //【API请求】----获取表格列表数据
            getViewMatchItemList(this.pageRequest).then(response => {
                response = response.result
                this.tableList = response.list
                this.tableTotal = response.total
                this.listLoading = false;
            }).catch((res) => {
                this.$message({message: res.msg, type: 'error'})
            })
        },
        getTypeList() {
            getJdMatchTypeList().then(response => {
                response = response.result
                this.typeList = response.content
            }).catch((res) => {
                this.$message({message: res.msg, type: 'error'})
            })
        },
        getItemList(typeId) {
            getListByTypeId({typeId: typeId}).then(response => {
                this.itemList = response.result
            }).catch((res) => {
                this.$message({message: res.msg, type: 'error'})
            })
        },
        getAllItemList() {
            getJdMatchItemList().then(response => {
                this.allItemList = response.result.content
            }).catch((res) => {
                this.$message({message: res.msg, type: 'error'})
            })
        },
        //根据比赛id获取赛程
        getFormatByMatchId(matchId) {
            getMatchFormatList({matchId: matchId}).then(response => {
                this.dataFormFormat = response.result
                var matchNum = response.result.formatList.length
                if(matchNum === 1){
                    this.matchNum = 0
                }else if(matchNum > 1){
                    this.matchNum = 1
                }
            }).catch((res) => {
                this.$message({message: res.msg, type: 'error'})
            })
        },
        //根据赛程id获取直播间信息
        getFormatLiveList(formatId) {
            getFormatLiveList({formatId: formatId}).then(response => {
                response = response.result
                this.tableListFormatLive = response.list
            }).catch((res) => {
                this.$message({message: res.msg, type: 'error'})
            })
        },
        getLiveUserList(matchCu) {
            getSysLiveUserList({userId: matchCu}).then(response => {
                this.liveUserList = response.result
            }).catch((res) => {
                this.$message({message: res.msg, type: 'error'})
            })
        },
        //查看赛程
        handleSetFormatLive(matchId,matchGroup,matchCu,itemIds) {
            this.matchId = matchId
            this.matchGroup = matchGroup
            this.matchCu = matchCu
            //赛程数量
            this.matchItemIds = itemIds
            //加载赛事主播
            this.getLiveUserList(this.matchCu)
            this.getFormatListVisible = true
            this.listLoadingFormat = false
            getFormatListPage({matchId: matchId}).then(response => {
                this.tableListFormat = response.result.list
            }).catch((res) => {
                this.$message({message: res.msg, type: 'error'})
            })
        },
        formatArrangeOrder(row){
            switch (row.arrangeOrder){
                case 1:
                    return "初赛"
                case 2:
                    return "复赛"
                case 3:
                    return "决赛"
                default:
                    return "决赛"
            }
        },
        showFormatLiveList() {
            this.handleFormatLive(this.formatId)
        },
        showFormatLiveUserList(){
            this.assignFormatMember(this.formatId)
        },
        showFormatUserList(){
            this.handleCreateUser()
        },
        showFormatLiveRecordUserList(){
            console.log(this.formatId, this.liveRecordId)
            this.formatMemberPageParam.id = this.liveRecordId;
            this.formatMemberPageParam.arrangeId = this.formatId;
            this.handleFormatLiveRecordUser(this.formatMemberPageParam)
        },
        //直播间
        handleFormatLive(formatId) {
            this.formatId = formatId
            this.getFormatLiveListVisible = true
            this.listLoadingFormatLive = true
            const params = {
                formatId: formatId,
                pageNum: this.pageRequestFormatLive.pageNum,
                pageSize: this.pageRequestFormatLive.pageSize
            }
            getFormatLiveListPage(params).then(response => {
                response = response.result
                this.tableListFormatLive = response.list
                this.tableTotalFormatLive = response.total
                this.listLoadingFormatLive = false;
            }).catch((res) => {
                this.$message({message: res.msg, type: 'error'})
            })
        },
        //直播间-查看参赛人员
        handleFormatLiveRecordUser(row) {
            this.liveRecordId = row.id
            this.formatId = row.arrangeId
            this.getFormatLiveRecordUserListVisible = true
            this.listLoadingFormatLiveRecordUser = true
            const params = {
                liveRecordId: row.id,
                formatId: row.arrangeId,
                pageNum: this.pageRequestFormatLiveRecordUser.pageNum,
                pageSize: this.pageRequestFormatLiveRecordUser.pageSize
            }
            getformatMemberList(params).then(response => {
                response = response.result
                this.tableListFormatLiveRecordUser = response.list
                this.tableTotalFormatLiveRecordUser = response.total
                this.listLoadingFormatLiveRecordUser = false;
            }).catch((res) => {
                this.$message({message: res.msg, type: 'error'})
            })
        },
        //分配参赛员
        //【参赛人员-按钮点击】--- 弹出参赛人员列表和新增参赛人员按钮
        assignFormatMember(formatId){
            let matchGroup = this.matchGroup;//1单人/2团体
            this.formatId = formatId
            this.getFormatLiveUserListVisible = true
            this.listLoadingFormatLiveUser = true
            this.getLiveRecordList(this.formatId)
            if(matchGroup === 1){
                const params = {
                    formatId: formatId,
                    pageNum: this.pageRequestFormatLiveUser.pageNum,
                    pageSize: this.pageRequestFormatLiveUser.pageSize
                }
                getformatMemberList(params).then(response => {
                    response = response.result
                    this.tableListFormatLiveUser = response.list
                    this.tableTotalFormatLiveUser = response.total
                    this.listLoadingFormatLiveUser = false;
                }).catch((res) => {
                    this.$message({message: res.msg, type: 'error'})
                })
            }else if(matchGroup === 2){
                const params = {
                    formatId: formatId,
                }
                getFormatLiveUserListGroup(params).then(response => {
                    response = response.result
                    this.tableListFormatLiveUser = response.list
                    this.tableTotalFormatLiveUser = response.total
                    this.listLoadingFormatLiveUser = false;
                }).catch((res) => {
                    this.$message({message: res.msg, type: 'error'})
                })
            }
        },
        //【按钮点击-分配参赛员】---删除用户
        handleDeleteLiveUser(row) {
            this.$confirm('确认删除该记录吗？', '提示', {}).then(() => {
                const params = {
                    formatId: row.formatId,
                    userId: row.userId,
                    liveRecordId: row.liveRecordId,
                    matchId: row.matchId,
                }
                handleDeleteLiveUser(params).then(response => {
                    console.log("response",response);
                    if(response.code == 500){
                        this.$message({ message: response.message, type: 'error' })
                        this.assignFormatMember(row.formatId)
                    }else{
                        this.$message({ message: response.message, type: 'success' })
                        this.assignFormatMember(row.formatId)
                    }
                }).catch(() => {
                    this.$message({message: '操作失败', type: 'error'})
                })
            }).catch(() => {
                this.$message({message: '操作失败', type: 'error'})
            })
        },
        //【按钮点击-分配参赛员】---删除组别
        handleDeleteGroupLiveUser(row) {
            this.$confirm('确认删除该记录吗？', '提示', {}).then(() => {
                const params = {
                    formatId: row.formatId,
                    groupId: row.groupId,
                    liveRecordId: row.liveRecordId,
                    matchId: row.matchId,
                }
                handleDeleteGroupLiveUser(params).then(response => {
                    console.log("response",response);
                    if(response.code == 500){
                        this.$message({ message: response.message, type: 'error' })
                        this.assignFormatMember(row.formatId)
                    }else{
                        this.$message({ message: response.message, type: 'success' })
                        this.assignFormatMember(row.formatId)
                    }
                }).catch(() => {
                    this.$message({message: '操作失败', type: 'error'})
                })
            }).catch(() => {
                this.$message({message: '操作失败', type: 'error'})
            })
        },
        //【按钮点击-团队赛事-查看团队人员列表】
        viewFormatLiveUser(row){
            this.getFormatMemberVisible = true
            this.listLoadingFormatMember = true


            // let formatId = this.formatId
            const params = {
                formatId: row.formatId,
                groupId: row.groupId,
            }
            getFormatMemberListByGroupId(params).then(response => {
                response = response.result
                this.tableListFormatMember = response.list
                this.tableTotalFormatMember = response.total
                this.listLoadingFormatMember = false;
            }).catch((res) => {
                this.$message({message: res.msg, type: 'error'})
            })
        },
        //【分配参赛员-所有直播间】
        getLiveRecordList(formatId) {
            const params = {
                formatId: formatId,
            }
            getFormatLiveRecordList(params).then(response => {
                this.liveRecordList = response.result
            }).catch((res) => {
                this.$message({message: res.msg, type: 'error'})
            })
        },
        //【分配参赛员-提交按钮】---提交分配
        assignFormatLiveUser(){
            let userId = null;
            let groupId = null;
            let formatId = this.formatId;//赛程id
            this.liveUserIds = [];

            if(!this.dataFormFormatLiveUser.recordId){
                this.$notify({title: '失败', message: '请选择直播间', type: 'error', duration: 2000})
                return ;
            }
            if(this.multipleSelection.length > 0){
                if(this.matchGroup === 1){
                    //这里存放userId
                    for(let i=0;i<this.multipleSelection.length;i++){
                        userId = this.multipleSelection[i].userId;
                    }
                    this.liveUserIds.push(
                        userId
                    )
                }else if(this.matchGroup === 2){
                    //这里存放groupId
                    for(let i=0;i<this.multipleSelection.length;i++){
                        groupId = this.multipleSelection[i].groupId;
                    }
                    this.liveUserIds.push(
                        groupId
                    )
                }
            }
            if(this.liveUserIds.length < 1){
                this.$notify({title: '失败', message: '请选择参赛员', type: 'error', duration: 2000})
                return ;
            }
            this.liveUserDataForm.formatArrangeId = formatId
            this.liveUserDataForm.liveUserList = this.liveUserIds
            this.liveUserDataForm.recordId = this.dataFormFormatLiveUser.recordId
            this.liveUserDataForm.matchId = this.matchId
            this.liveUserDataForm.matchType = this.matchGroup
            setMatchLiveUser(this.liveUserDataForm).then((res)=>{
                try {
                    if (res.code === 0) {
                        this.liveUserDataForm = {}// 重置表单数据
                        this.assignFormatMember(formatId)// 重新获取表格数据// 重新获取表格数据
                        this.$notify({title: '成功', message: '保存成功', type: 'success', duration: 2000})
                    }
                    this.editLoading = false// 关闭loading框
                } catch (e) {
                    throw e
                }
            })
        },
        //表格数据筛选
        handleFilter() {
            this.pageRequest.searchParam = this.searchParam
            this.getList()
        },
        //【按钮点击】--- 弹出新增表单
        handleCreate() {
            this.operation = true;
            this.initDataForm();
            this.areaCasResult = {}
            this.initDataFormFormat()
            this.dataForm.bannerList = '';
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
                this.editLoading = false;
            })
        },
        //【按钮点击】--- 弹出编辑表单
        handleUpdate(row) {
            this.operation = false;
            const provinceCode = row.provinceCode + ""
            const cityCode = row.cityCode + ""
            const countryCode = row.areaCode + ""
            this.typeId = row.type
            this.getFormatByMatchId(row.id)
            this.areaCasResult = {provinceCode, cityCode, countryCode}
            this.dataForm = Object.assign({}, row)
            if(this.dataForm.matchType === 1){
                this.dataForm.itemIdStr = Number(row.itemIds)
            }else{
                const ids = []
                if (row.itemIds.indexOf(",") !== -1) {
                    row.itemIds.split(",").forEach(i => {
                        ids.push(Number(i))
                    })
                } else {
                    ids.push(Number(row.itemIds))
                }
                this.dataForm.itemIdStr = ids
            }
            this.getItemList(row.type)
            //显示编辑菜单
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
                this.editLoading = false;
            })
        },
        //保存表单数据
        saveFormData() {
            let res
            this.$refs['dataForm'].validate(async (valid) => {
                if (!valid) {
                    return false;
                }
                this.editLoading = true;
                //【API请求】----保存数据
                if (this.dataFormFormat.formatList.length > 0) {
                    this.dataForm.format = JSON.stringify(this.dataFormFormat)
                }
                if(this.delFormatList.length > 0){
                    this.dataForm.delFormatList = JSON.stringify(this.delFormatList)
                }

                var matchNum = this.matchNum
                if(matchNum === null){
                    this.$notify({title: '失败', message: '请设置比赛规则', type: 'error', duration: 2000})
                    this.editLoading = false// 关闭loading框
                    return;
                }
                if(matchNum === 0 ){//单场
                    if(this.dataFormFormat.formatList.length > 1){
                        this.$notify({title: '失败', message: '单场比赛,只能设置一个赛程', type: 'error', duration: 2000})
                        this.editLoading = false// 关闭loading框
                        return;
                    }
                }else if(matchNum === 1){//多场
                    if(this.dataFormFormat.formatList.length !== 3){
                        this.$notify({title: '失败', message: '晋级赛,赛程必须是三个', type: 'error'})
                        this.editLoading = false// 关闭loading框
                        return;
                    }
                }

                //验证赛程必填项
                for(var i = 0;i<this.dataFormFormat.formatList.length;i++){
                    if(!this.dataFormFormat.formatList[i].startTime){
                        this.$notify({title: '失败', message: '第'+(i+1)+'个赛程的的开始时间不能为空', type: 'error'})
                        this.editLoading = false// 关闭loading框
                        return;
                    }
                    if(!this.dataFormFormat.formatList[i].endTime){
                        this.$notify({title: '失败', message: '第'+(i+1)+'个赛程的的结束时间不能为空', type: 'error'})
                        this.editLoading = false// 关闭loading框
                        return;
                    }
                    if(this.dataFormFormat.formatList[i].updateType === ""){
                        this.$notify({title: '失败', message: '第'+(i+1)+'个赛程的的晋级方式不能为空', type: 'error'})
                        this.editLoading = false// 关闭loading框
                        return;
                    }
                    if(this.dataFormFormat.formatList[i].updateType === 0){//如果是自动，需要选择晋级人数和晋级分数至少一个
                        if((this.dataFormFormat.formatList[i].promotionNum < 1 && this.dataFormFormat.formatList[i].promotionScore < 1)){
                            this.$notify({title: '失败', message: '第'+(i+1)+'个赛程的的晋级人数和晋级分数至少填一个', type: 'error'})
                            this.editLoading = false// 关闭loading框
                            return;
                        }
                    }
                    // if(this.dataFormFormat.formatList[i].promotionScore < 1){
                    //     this.$notify({title: '失败', message: '第'+(i+1)+'个赛程的的晋级分数不能为空', type: 'error'})
                    //     this.editLoading = false// 关闭loading框
                    //     return;
                    // }
                }
                if(this.dataForm.matchType === 1){
                    this.dataForm.itemIds = this.dataForm.itemIdStr
                }else{
                    this.dataForm.itemIds = this.dataForm.itemIdStr.join(",");
                }
                //处理全国 全省 全市
                if(this.dataForm.province === '全国'){
                    this.dataForm.provinceCode = ''
                    this.dataForm.cityCode = ''
                    this.dataForm.areaCode = ''
                }
                if(this.dataForm.city === '全省'){
                    this.dataForm.cityCode = ''
                    this.dataForm.areaCode = ''
                }
                if(this.dataForm.area === '全市'){
                    this.dataForm.areaCode = ''
                }
                if (this.dataForm.id === null || this.dataForm.id === '') {
                    res = await saveJdMatch(this.dataForm)
                } else {
                    res = await editJdMatch(this.dataForm)
                }
                try {
                    if (res.code === 0) {
                        this.dialogFormVisible = false// 关闭表单页面
                        this.initDataForm()// 重置表单数据
                        this.getList()// 重新获取表格数据
                        this.delFormatList = []
                        this.$notify({title: '成功', message: '保存成功', type: 'success', duration: 2000})
                    }
                    this.editLoading = false// 关闭loading框
                } catch (e) {
                    throw e
                }
            })
        },
        //【按钮点击】---删除行
        handleDelete(row) {
            this.$confirm('确认删除该记录吗？', '提示', {}).then(() => {
                //【API请求】---- 删除数据
                deleteJdMatch(row.id).then(() => {
                    this.$message({message: '操作成功', type: 'success'})
                    this.getList();
                })
            }).catch(() => {
                this.$message({message: '操作失败', type: 'error'})
            });
        },
        handlerMatchType(value) {
            this.dataForm.matchType = value
            this.dataForm.itemIds = ''
            if(this.dataForm.matchType === 1){
                this.dataForm.itemIdStr = ''
            }else{
                this.dataForm.itemIdStr = []
            }
        },
        handlerMatchGroup(value){
            //1单人 2团体
            if(value === 1){
                this.dataForm.matchType = 1
            }else{
                this.dataForm.matchType = 3
            }
            if(this.dataForm.matchType === 1){
                this.dataForm.itemIdStr = ''
            }else{
                this.dataForm.itemIdStr = []
            }
        },
        //添加赛程
        addItem() {
            if(this.matchNum === 0){//单场
                if(this.dataFormFormat.formatList.length === 1){
                    this.$notify({title: '失败', message: '当前是单场赛,不可添加多个赛程', type: 'error', duration: 2000})
                    return;
                }
            }else if(this.matchNum === 1){//3场
                if(this.dataFormFormat.formatList.length === 3){
                    this.$notify({title: '失败', message: '当前是晋级赛,必须是3个赛程', type: 'error', duration: 2000})
                    return;
                }
            }
            this.dataFormFormat.formatList.push({
                id: '',
                startTime: '',
                endTime: '',
                promotionNum: '',
                promotionScore: '',
                updateType: '',
            })

        },
        //移除赛程
        deleteItem(item) {
            const index = this.dataFormFormat.formatList.indexOf(item);
            if (index !== -1) {
                this.dataFormFormat.formatList.splice(index, 1)
                this.delFormatList.push(item.id)
            }
        },

        //【按钮点击】--- 弹出新增表单
        handleCreateLive() {
            this.initDataFormLive()
            this.dialogFormVisibleFormatLive = true
            this.$nextTick(() => {
                this.$refs['dataFormFormatLive'].clearValidate()
                this.editLoading = false;
            })
        },

        //【按钮点击】--- 弹出编辑表单
        handleUpdateLive(row) {
            this.getFormatLiveList(row.arrangeId)
            this.dataFormFormatLive = Object.assign({}, row)
            //显示编辑菜单
            this.dialogFormVisibleFormatLive = true
            this.$nextTick(() => {
                this.$refs['dataFormFormatLive'].clearValidate()
                this.editLoadingFormatLive = false;
            })
        },
        //保存表单数据
        saveFormDataLive() {
            let res
            this.$refs['dataFormFormatLive'].validate(async (valid) => {
                if (!valid) {
                    return false;
                }
                this.editLoadingFormatLive = true;
                this.dataFormFormatLive.matchId = this.matchId
                this.dataFormFormatLive.arrangeId = this.formatId
                //【API请求】----保存数据
                if (this.dataFormFormatLive.id === null || this.dataFormFormatLive.id === '') {
                    res = await saveFormatLive(this.dataFormFormatLive)
                } else {
                    res = await editFormatLive(this.dataFormFormatLive)
                }
                try {
                    if (res.code === 0) {
                        this.dialogFormVisibleFormatLive = false// 关闭表单页面
                        this.initDataFormLive()// 重置表单数据
                        this.handleFormatLive(this.formatId)// 重新获取表格数据
                        this.$notify({title: '成功', message: '保存成功', type: 'success', duration: 2000})
                    }
                    this.editLoadingFormatLive = false// 关闭loading框
                } catch (e) {
                    throw e
                }
            })
        },
        //【按钮点击】---删除行
        handleDeleteLive(row) {
            this.$confirm('确认删除该记录吗？', '提示', {}).then(() => {
                //【API请求】---- 删除数据
                deleteFormatLive(row.id).then(() => {
                    this.$message({message: '操作成功', type: 'success'})
                    this.getFormatLiveList(this.formatId);
                })
            }).catch(() => {
                this.$message({message: '操作失败', type: 'error'})
            });
        },
        //初始化表单数据，重新渲染
        initDataForm() {
            this.dataForm = {
                id: '',
                name: '',
                province: '',
                provinceCode: '',
                city: '',
                cityCode: '',
                area: '',
                areaCode: '',
                type: '',
                description: '',
                signCount: '',
                matchGroup: '',
                matchType: '',
                itemIds: '',
                itemIdStr: [],
                payType: '',
                startTime: '',
                endTime: '',
                cu: '',
                ct: '',
                state: '',
                remark: '',
                signPrice: '',
                isCenterPush: '',
                itemNames: '',
                chatTime: '',
                isPublic: '',
                bannerList: '',
                format: {},
            };
        },
        initDataFormFormat() {
            this.dataFormFormat = {
                formatList: [{
                    startTime: '',
                    endTime: '',
                    promotionNum: '',
                    promotionScore: '',
                    updateType: '',
                }]
            }
        },
        initDataFormLive() {
            this.dataFormFormatLive = {
                id: '',
                title: '',
                liveId: '',
                liveLogo: '',
            }
        },
        //【分配参赛员-初始化数据】
        initDataFormUser() {
            this.dataFormFormatLiveUser = {
                liveUserList: [],
                recordId: '',
                matchId: '',
                formatArrangeId: '',
                matchType: '',
            }
        },

        //关闭表单弹出框
        closeDialog() {
            this.$refs['dataForm'].resetFields();
            this.dialogFormVisible = false
            this.getList();
            this.initDataForm();
            this.dataForm.bannerList = '';
        },
        // 重置按钮
        searchReset() {
            this.searchParam = {}
            this.pageRequest = {pageNum: 1, pageSize: 10}
            this.getList()
        },
        //关闭赛程表单
        closeDialogFormat() {
            this.getFormatListVisible = false
        },
        closeDialogFormatLive() {
            this.getFormatLiveListVisible = false
        },
        closeDialogFormatLiveRecordUser(){
            this.getFormatLiveRecordUserListVisible = false
        },
        //团队参赛人员列表
        closeDialogFormatMember() {
            this.getFormatMemberVisible = false
        },
        //关闭分配参赛员页面
        closeDialogFormatLiveUser() {
            this.getFormatLiveUserListVisible = false
        },
        closeDialogFormatUser(){
            this.dialogFormVisibleFormatUser = false

        },

        returnFormatLive() {
            this.$refs['dataFormFormatLive'].resetFields();
            this.dialogFormVisibleFormatLive = false
        },
        //弃赛操作
        giveUpFormat(row) {
            this.$confirm('确认操作弃赛吗？', '提示', {}).then(() => {
                console.log("赛成数量",this.matchItemIds)
                const ids = []
                if (this.matchItemIds.indexOf(",") !== -1) {
                    this.matchItemIds.split(",").forEach(i => {
                        ids.push(Number(i))
                    })
                } else {
                    ids.push(Number(this.matchItemIds))
                }
                console.log("赛程ids",ids)

                //遍历数组
                ids.forEach(i => {
                    this.scoreParamDataForm.userId = 0
                    this.scoreParamDataForm.itemId = i
                    this.scoreParamDataForm.formatId = row.formatId
                    this.scoreParamDataForm.scoreInfoList.push({
                        groupId: row.groupId,
                        userId: row.userId,
                        score: '0',
                    })
                    console.log("this.scoreParamDataForm",this.scoreParamDataForm)
                    giveUpFormatList(this.scoreParamDataForm);
                    //初始化集合
                    this.initScoreParamDataForm()
                })

                //刷新当前页
                // this.handleFormatLiveRecordUser(row)
                const params = {
                    liveRecordId: row.liveRecordId,
                    formatId: row.formatId,
                    pageNum: this.pageRequestFormatLiveRecordUser.pageNum,
                    pageSize: this.pageRequestFormatLiveRecordUser.pageSize
                }
                getformatMemberList(params).then(response => {
                    response = response.result
                    this.tableListFormatLiveRecordUser = response.list
                    this.tableTotalFormatLiveRecordUser = response.total
                    this.listLoadingFormatLiveRecordUser = false;
                }).catch((res) => {
                    this.$message({message: res.msg, type: 'error'})
                })
                //弹出提示框
                this.$message({message: '操作成功', type: 'error'})
            }).catch(() => {
                this.$message({message: '操作失败', type: 'error'})
            });

        },
        initScoreParamDataForm() {
            this.scoreParamDataForm = {
                userId:'',
                itemId:'',
                formatId:'',
                scoreInfoList:[],
            }
        },



    },
    created() {
        this.getList();
        this.getTypeList();
        this.getAllItemList();
        // this.getLiveUserList();
    },
}
</script>
